package com.ruoyi.network;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class NettyServer {

    @Autowired
    private CustomServer2Handler customServer2Handler;

    public void startServer(int port) {
        //EventLoopGroup   事件循环组    线程池    线程   轮询-监测事件

        //监测客户端连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //监测客户端发送的数据
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            //TCP                        Netty
            //服务器端：ServerSocket      ServerBootstrap
            //客户端：Socket              Bootstrap

            //ServerBootstrap 服务器启动类     ServerSocket
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)    //给服务器启动类设置事件循环组（线程池）
                    .channel(NioServerSocketChannel.class)  //设置通道为NioServerSocketChannel
                    .option(ChannelOption.SO_BACKLOG, 128)  //设置TCP底层通讯的参数 - ChannelOption.SO_BACKLOG
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //通道Channel
                            //Pipeline 管道    链
                            ChannelPipeline channelPipeline = socketChannel.pipeline();
                            //channelPipeline.addLast(new StringEncoder());//添加字符串编码器    StringEncoder是netty内置的一个编码器
                            //channelPipeline.addLast(new LineBasedFrameDecoder(1000));

                            //ByteBuf delimiter = Unpooled.copiedBuffer("$$$$$".getBytes());

                            //channelPipeline.addLast(new DelimiterBasedFrameDecoder(20, delimiter));

                            //channelPipeline.addLast(new StringDecoder());//添加字符串解码器    StringDecoder是netty内置的一个解码器

                            LengthFieldBasedFrameDecoder decoder = new LengthFieldBasedFrameDecoder(27, 10, 1, 3, 0);

                            channelPipeline.addLast(decoder);

                            //channelPipeline.addLast(new CustomServerHandler());
                            channelPipeline.addLast(customServer2Handler);
                        }
                    });

            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }


}
